package ru.amse.tsyganov.jumleditor.validator;

import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;

public class ProblemsTable {
	
	public static final String COLUMN_NAME = "Description";
	
	private final Table problemsTable;
	
	private final TableViewer problemsTableViewer;
	
	private final ProblemsContentProvider problemsContentProvider;
	
	private final ProblemsCellModifier problemsCellModifier;
	
	private ProblemsList problemsList;
	
	public ProblemsTable(Composite parent, int tableWidth) {
		
		problemsTable = new Table(parent, 
				SWT.FULL_SELECTION | SWT.MULTI | 
				SWT.V_SCROLL | SWT.H_SCROLL);
	
		initTable(tableWidth);
		
		problemsTableViewer = new TableViewer(problemsTable);
		
		problemsContentProvider = new ProblemsContentProvider(
				new ProblemsList());
		
		problemsCellModifier = new ProblemsCellModifier();
		
		initTableViewer();
	}

	private void initTableViewer() {
		problemsTableViewer.setUseHashlookup(true);
		
		problemsTableViewer.setLabelProvider(new ProblemsLabelProvider());
		
		problemsTableViewer.setContentProvider(problemsContentProvider);
		
		problemsTableViewer.setCellEditors(new CellEditor[] {
			new TextCellEditor(problemsTable),
		});
		
		problemsTableViewer.setColumnProperties(
				new String[] {COLUMN_NAME});
				
		problemsTableViewer.setCellModifier(problemsCellModifier);
		
		problemsTableViewer.setInput(new ProblemsList());
	}

	private void initTable(int tableWidth) {
		TableColumn descriptionColumn = 
			new TableColumn(problemsTable, SWT.LEFT);
		descriptionColumn.setText(COLUMN_NAME);
		descriptionColumn.setWidth(tableWidth - 20);
		
		problemsTable.setHeaderVisible(true);
		problemsTable.setLinesVisible(true);
	}

	public Table getTable() {
		return problemsTable;
	}

	public void setSource(ProblemsList problemsList) {
		this.problemsList = problemsList;
		problemsTableViewer.setInput(problemsList);
		problemsTableViewer.refresh();
	}
	
	public void clear() {
		problemsTableViewer.setInput(new ProblemsList());
	}

	public ProblemsList getProblemsList() {
		return problemsList;
	}
}
